package com.xunfang.demo.servlet3;

import com.xunfang.demo.entity.UserDemo;
import com.xunfang.demo.service.UserService;
import com.xunfang.demo.service.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@WebServlet(name = "RegisterServlet", urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1.获取指定的请求参数
        String userName = request.getParameter("userName");
        System.out.println("userName = " + userName);
        //2.获取参数中的一键多值
        String[] chks = request.getParameterValues("chk");
        System.out.println("chks = " + Arrays.toString(chks));
        //3.获取提交的所有参数
        Map<String, String[]> maps = request.getParameterMap();
        UserDemo userDemo = new UserDemo();
        /*Set<String> keys = maps.keySet();
        for (String key : keys) {
            String[] strings = maps.get(key);
            System.out.println(key + "..." + Arrays.toString(strings));
        }*/
        //从前端传递的日期是String格式，但是实体中是Date类型，不能直接转换
        //使用日期转换器，来转换日期格式
        DateConverter dc = new DateConverter();
        //设置转换格式
        dc.setPatterns(new String[]{"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"});
        //实现注册转换
        ConvertUtils.register(dc, Date.class);
        //populate:可以直接把map中的数据赋值给实体类的属性！！！
        //注意：表单中的name属性的名字必须要跟实体中的属性的名字完全一致！！！
        try {
            BeanUtils.populate(userDemo,maps);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //爱好单独处理
        userDemo.setChk(Arrays.toString(chks));
        System.out.println(userDemo);
        //调用业务层方法
        boolean bool = userService.addUser(userDemo);
        if(bool){
            response.getWriter().write("<h1>恭喜你，注册成功！5秒之后，跳转到登录页面！</h1>");
            //refresh: 响应头，表示多少秒之后，跳转到指定的url
            response.setHeader("refresh","5;url="+request.getContextPath()+"/index.jsp");
        }else{
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }
    }
}
